<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleCancel" center top="5vh" width="800px">
      <el-form ref="editFormRef" :model="editForm" :rules="rules" size="small" label-width="100px">

          <el-form-item label="设备编号" prop="sourceId" :label-width="labelWidth" class="line">
            <el-input :disabled="!isEditNo" clearable placeholder="请输入设备编号" v-model="editForm.sourceId"></el-input>
          </el-form-item>
          <el-form-item label="设备名称" prop="eqptName" :label-width="labelWidth" class="line">
            <el-input placeholder="请输入设备名称" v-model="editForm.eqptName"
            ></el-input>
          </el-form-item>

          <el-form-item label="楼宇" prop="buildId" :label-width="labelWidth" class="line">
            <el-select v-model="editForm.buildId" class="selectWidth"
            clearable placeholder="请选择楼宇" @change="changeBuildFn">
              <el-option class="optionsWidth"
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- <el-input disabled placeholder="请输入楼宇" v-model="editForm.buildName"></el-input> -->
          </el-form-item>
          <el-form-item label="设备类型一级" prop="firstTypeId" :label-width="labelWidth" class="line">
            <!-- <el-input placeholder="请输入设备类型一级" v-model="editForm.eqptType"></el-input> -->
            <el-select clearable filterable @change="firstTypeChange" v-model="editForm.firstTypeId"  class="selectWidth" placeholder="请选择设备类型一级">
                <el-option
                  v-for="item in firstTypeList"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                >
                </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="楼层" prop="floorId" :label-width="labelWidth" class="line">
            <el-select v-model="editForm.floorId"
            ref="floorRef"
              @change="ChangeFloor"
             class="selectWidth" clearable placeholder="请选择楼层">
              <el-option class="optionsWidth"
                v-for="item in floorList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- <el-input disabled placeholder="请输入楼层" v-model="editForm.floorName"></el-input> -->
          </el-form-item>

          <!-- <el-col :span="12">
            <el-form-item label="设备类型">
              <el-select
                disabled
                style="width:100%"
                v-model="editForm.eqptType"
                placeholder="请选择设备类型"
              >
                <el-option
                  v-for="item in deviceTypeList"
                  :key="item.eqptType"
                  :label="item.eqptName"
                  :value="item.eqptType"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-form-item label="设备类型二级" prop="secondTypeId" :label-width="labelWidth" class="line">
            <el-select clearable filterable
              v-model="editForm.secondTypeId"
             class="selectWidth" placeholder="请输入设备类型二级">
                <el-option
                  v-for="item in secondTypeList"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                >
                </el-option>
            </el-select>
            <!-- <el-input placeholder="请输入设备类型二级" v-model="editForm.eqptType"></el-input> -->
          </el-form-item>

          <el-form-item label="区域/房间" prop="areaId" :label-width="labelWidth" class="line">
            <el-select v-model="editForm.areaId"
             class="selectWidth" clearable placeholder="请选择区域/房间">
              <el-option class="optionsWidth"
                v-for="item in areaList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <!-- <el-input disabled placeholder="请输入楼层" v-model="editForm.floorName"></el-input> -->
          </el-form-item>

          <el-form-item label="供应商名称" prop="supplierName" :label-width="labelWidth" class="line">
            <el-input placeholder="请输入供应商名称" v-model="editForm.supplierName"></el-input>
          </el-form-item>

          <el-form-item label="设备标签" prop="eqptLabelId" :label-width="labelWidth" class="line">
            <select-tree
              :width="260"
              :isNodeParams="true"
              placeholder="请选择设备标签"
              v-model="editForm.labelTree"
              :departments="eqptLabelTreeList"
            />
            <!-- <el-select
              v-model="editForm.eqptLabelId"
              class="selectWidth"
              multiple
              collapse-tags
              clearable
              placeholder="请选择设备标签"
            >
              <el-option class="optionsWidth"
                v-for="item in labelList"
                :key="item.labelId"
                :label="item.labelName"
                :value="item.labelId"
              ></el-option>
            </el-select> -->
            <!-- <el-input disabled placeholder="请输入楼层" v-model="editForm.floorName"></el-input> -->
          </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleOk('editFormRef')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import pick from 'lodash.pick'
import SelectTree from '@/components/selectTree'
import {
  getDeviceTypeList,
  getListByTag,
  getLabelSelect,
  addEqptData,
  modifyEqpt,
  getEqptLabelTreeList
} from '@/views/children/safety/js/device'
import { validateStrLen30, validateStrLenNo50 } from '@/utils/validate'
export default {
  name: 'MaintainModal',
  components: { SelectTree },
  data () {
    return {
      title: '添加设备',
      dialogVisible: false,
      isEditNo: true,
      model: {},
      labelWidth: '120px',
      editForm: {
        areaId: '',
        areaName: '',
        buildId: '',
        buildName: '',
        eqptLabelId: [],
        eqptName: '',
        firstTypeId: '',
        secondTypeId: '',
        eqptTypeId: '',
        floorId: '',
        floorName: '',
        sourceId: '',
        supplierName: ''
      },
      firstTypeId: '',
      // secondTypeId: '',
      labelList: [],
      firstTypeList: [], // 一级列表
      secondTypeList: [], // 二级列表
      buildList: [],
      enumBuild: {},
      enumFloor: {},
      enumArea: {},
      floorList: [],
      areaList: [],
      areaIdList: [],
      rules: {
        sourceId: [
          { required: true, message: '请输入设备编号!' },
          { validator: validateStrLenNo50, trigger: 'blur' }
        ],
        eqptName: [
          { required: true, message: '请输入设备名称!' },
          { validator: validateStrLen30, trigger: 'blur' }
        ],
        supplierName: [{ required: false, validator: validateStrLen30, trigger: 'blur' }],
        firstTypeId: [{ required: true, message: '请选择一级设备类型!' }],
        secondTypeId: [{ required: true, message: '请选择二级设备类型!' }],
        buildId: [{ required: true, message: '请选择楼宇!' }],
        floorId: [{ required: true, message: '请选择楼层!' }],
        areaId: [{ required: true, message: '请选择区域!' }]
      },
      eqptLabelTreeList: []
    }
  },
  watch: {
    firstTypeId: {
      deep: true,
      handler: function (value) {
        if (!value) return
        this.$nextTick(() => {
          this.getTypeList({ typeLevel: 2, typeParentId: value }).then((resolve, reject) => {
            this.secondTypeList = resolve
          })
        })
      }
    }
  },
  props: {
    eqptNo: {
      type: String,
      required: true
    }
  },
  mounted () {
    this.getListByTagQuery()
    this.getLabelList()
    this.getEqptLabelTreeList()
    this.getTypeList({ typeLevel: 1 }).then((resolve, reject) => {
      this.firstTypeList = resolve
    })
  },
  methods: {
    // 新增
    add () {
      // 获取一级类型列表
      this.edit({})
    },
    // 编辑
    async edit (row) {
      this.title = '新增设备'
      this.dialogVisible = true
      console.log(row)
      if (row.eqptId) {
        // 编号不可更改
        this.isEditNo = false
        this.title = '编辑设备'
        this.model = { ...row }
        if (row.buildId) {
          await this.changeBuildFn(row.buildId)
        }
        if (row.floorId) {
          await this.ChangeFloor(row.floorId)
        }
        await this.getTypeList({ typeLevel: 2, typeParentId: row.eqptParentTypeId || row.eqptTypeId }).then((resolve, reject) => {
          this.secondTypeList = resolve
        })
        this.editForm = {
          ...row,
          areaId: (!row.buildId) && (!row.floorId) ? +row.areaId : '',
          buildId: +row.buildId || '',
          floorId: +row.floorId || '',
          firstTypeId: row.eqptParentTypeId || row.eqptTypeId,
          secondTypeId: row.eqptParentTypeId ? row.eqptTypeId : ''
        }
        this.editForm.buildId = this.enumBuild[+row.buildId] ? +row.buildId : ''
        this.editForm.floorId = this.editForm.buildId && this.enumFloor[+row.floorId] ? +row.floorId : ''
        this.editForm.areaId = this.enumArea[+row.areaId] ? +row.areaId : ''
        // this.editForm.secondTypeId = row.eqptParentTypeId ? row.eqptTypeId
        // this.editForm.secondTypeId = row.eqptParentTypeId ? row.eqptTypeId : ''
      }
      this.$nextTick(() => {
        // DOM 更新了
        this.$refs['editFormRef'].clearValidate()
      })
    },

    // 判断区域是否存在
    async isArea () {
      this.areaList.forEach(item => {
        this.areaIdList.push(item.id)
      })
    },

    // 获取设备类型列表
    async getTypeList (params) {
      try {
        let res = await getDeviceTypeList(params)
        if (res.code === 0) {
          return res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (e) {}
    },

    // 改变一级类型的值
    firstTypeChange (val) {
      this.editForm.secondTypeId = ''
      this.getTypeList({ typeLevel: 2, typeParentId: val }).then((resolve, reject) => {
        this.secondTypeList = resolve
      })
    },
    async getEqptLabelTreeList () {
      try {
        const res = await getEqptLabelTreeList()
        if (res.code === 0) {
          this.eqptLabelTreeList = res.data
        }
      } catch (e) {}
    },

    // 获取楼栋下拉列表数据
    async getListByTagQuery () {
      let query = {
        parentId: 0,
        tag: 1
      }
      let res = await getListByTag(query)
      this.buildList = res.data
      // 生成楼栋枚举 便于后期取相应label值
      res.data.forEach(item => {
        this.enumBuild[item.id] = item.name
      })
    },
    // 改变楼栋的值
    async changeBuildFn (val) {
      this.editForm.floorId = ''
      if (val === '') return
      let query = {
        parentId: val,
        tag: 2
      }
      let res = await getListByTag(query)
      this.floorList = res.data
      // 生成楼层枚举 便于后期取相应label值
      res.data.forEach(item => {
        this.enumFloor[item.id] = item.name
      })
    },
    // 改变楼层
    async ChangeFloor (val) {
      this.editForm.areaId = ''
      if (val === '') return
      let query = {
        parentId: val,
        tag: 3
      }
      let res = await getListByTag(query)
      this.areaList = res.data
      // this.isArea()
      // 生成区域枚举 便于后期取相应label值
      res.data.forEach(item => {
        this.enumArea[item.id] = item.name
      })
      // 获取区域
      query = {
        parentId: val,
        tag: 4
      }
      let areaRes = await getListByTag(query)
      console.log(areaRes)
      areaRes.data.forEach(item => {
        this.areaList.push(item)
        this.enumArea[item.id] = item.name
      })
    },

    // 标签下拉列表数据
    async getLabelList () {
      try {
        let params = {
          labelName: ''
        }
        let res = await getLabelSelect(params)
        if (res.code === 0) {
          this.labelList = res.data
        } else {
          this.$message.error(res.msg)
        }
      } catch (e) {}
    },
    // 提交表单
    handleOk (editFormRef) {
      this.$refs[editFormRef].validate(async valid => {
        if (valid) {
          if (this.editForm.eqptId) {
            // 编辑
            let editQuery = {
              areaId: this.editForm.areaId,
              areaMapX: this.editForm.areaMapX,
              areaMapY: this.editForm.areaMapY,
              buildId: this.editForm.buildId,
              eqptId: this.editForm.eqptId,
              eqptLabelId: this.editForm.eqptLabelId,
              eqptName: this.editForm.eqptName,
              floorId: this.editForm.floorId,
              mapX: this.editForm.mapX,
              mapY: this.editForm.mapY,
              supplierName: this.editForm.supplierName,
              tenantNo: this.editForm.tenantNo,
              userNo: this.editForm.userNo,
              labelTree: this.editForm.labelTree
            }
            editQuery.labelIdList = this.editForm.labelTree?.length ? this.editForm.labelTree.filter(n => !n.children).map(n => n.id) : []
            editQuery.eqptTypeId = this.editForm.secondTypeId ? this.editForm.secondTypeId : editQuery.firstTypeId
            editQuery.areaName = this.enumArea[this.editForm.areaId] || ''
            editQuery.buildName = this.enumBuild[this.editForm.buildId]
            editQuery.floorName = this.enumFloor[this.editForm.floorId]
            // delete editQuery.firstTypeId
            // delete editQuery.secondTypeId
            // delete editQuery.eqptLabelName
            console.log(this.editForm)
            console.log(editQuery)
            let res = await modifyEqpt(editQuery)
            if (res.code === 0) {
              this.$emit('ok')
              this.handleCancel()
            } else {
              this.$message.error(res.msg)
            }
            return
          }
          // 新增
          let res
          let parmas = {
            ...this.editForm
          }
          parmas.labelIdList = this.editForm.labelTree?.length ? this.editForm.labelTree.filter(n => !n.children).map(n => n.id) : []
          parmas.eqptTypeId = this.editForm.secondTypeId ? this.editForm.secondTypeId : parmas.firstTypeId
          parmas.areaName = this.enumArea[this.editForm.areaId] || ''
          parmas.buildName = this.enumBuild[this.editForm.buildId]
          parmas.floorName = this.enumFloor[this.editForm.floorId]
          delete parmas.firstTypeId
          delete parmas.secondTypeId
          console.log(parmas)
          res = await addEqptData(parmas)
          if (res.code === 0) {
            this.$emit('ok')
            this.handleCancel()
          } else {
            this.$message.warning(res.msg)
          }
        }
      })
    },

    // 取消
    handleCancel () {
      this.model = {}
      this.editForm = {}
      this.areaIdList = []
      this.$refs.editFormRef.resetFields()
      this.$parent.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
// /deep/ .el-input{
//   width: 355px;
// }
.selectWidth {
  width: 230px;
}
.line{
  display: inline-block;
  width: 350px;
}
.optionsWidth {
  width: 230px;
  // background-color:black;
}
</style>
